/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tpdisenio2009.mvp.presenter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import tpdisenio2009.Tpdisenio2009App;
import tpdisenio2009.model.beans.Person;
import tpdisenio2009.model.beans.User;
import tpdisenio2009.mvp.display.CreateFantasyTeamViewImpl;
import tpdisenio2009.mvp.display.CreateUserViewImpl;
import tpdisenio2009.mvp.display.LoginView;
import tpdisenio2009.services.UserService;

/**
 *
 * @author DeuterioX
 */
public class LoginPresenter extends DefaultPresenter<LoginView> {

    private final UserService service;

    private ActionListener login;

    private ActionListener newUser;

    private ActionListener recoverPassword;

    private ItemListener documentTypeChange;

    private WindowListener exitAPP;

    public LoginPresenter( LoginView view ) {
        super( view );

        service = new UserService();
        getView().setDocumentType( service.getDocumentType() );

        bind();
    }

    private final boolean validate() {
        if ( getView().getDocumentType() == null) {
            getView().showError( getView().DOCUMENT_TYPE,
                    "<html>El campo <strong>tipo de document</strong> es obligatorio,<br>y no puede dejarse en blanco.</html>",
                    "Error:Campo obligatorio incompleto" );
            return false;
        } else if ( getView().getDocument().isEmpty() ) {
            getView().showError( getView().DOCUMENT,
                    "<html>El campo <strong>documento</strong> es obligatorio,<br>y no puede dejarse en blanco.</html>",
                    "Error:Campo obligatorio incompleto" );
            return false;
        } else if ( getView().getPassword().isEmpty() ) {
            getView().showError( getView().PASSWORD,
                    "<html>El campo <strong>contraseña</strong> es obligatorio,<br>y no puede dejarse en blanco.</html>",
                    "Error:Campo obligatorio incompleto" );
            return false;
        } else if ( service.getPersonByDocument( getView().getDocument(), getView().getDocumentType() ) == null ) {
            getView().showError( getView().DOCUMENT_TYPE,
                    "<html>El <strong>usuario</strong> ingresado no existe.</html>",
                    "Error:usuario inexistente" );
            return false;
        } else if ( !service.getPersonByDocument( getView().getDocument(), getView().getDocumentType() ).getPassword().equals( getView().getPassword() ) ) {
            getView().showError( getView().DOCUMENT_TYPE,
                    "<html>Tipo de documento, documento o contraseña incorrectas.</html>",
                    "Error:datos incorrectos" );
            return false;
        } else {
            return true;
        }
    }

    public void bind() {

        exitAPP = new WindowListener() {

            public void windowOpened(WindowEvent e) {
               // System.out.println("windowOpened");
            }

            public void windowClosing(WindowEvent e) {
                 System.exit(0);
            }

            public void windowClosed(WindowEvent e) {
               // throw new UnsupportedOperationException("Not supported yet.3");
            }

            public void windowIconified(WindowEvent e) {
               // throw new UnsupportedOperationException("Not supported yet.4");
            }

            public void windowDeiconified(WindowEvent e) {
                throw new UnsupportedOperationException("Not supported yet.5");
            }

            public void windowActivated(WindowEvent e) {
               // System.out.println("windowActivated");
            }

            public void windowDeactivated(WindowEvent e) {
//                throw new UnsupportedOperationException("Not supported yet.7");
            }
        };
        getView().addExitAPPListener( exitAPP );
        newUser = new ActionListener() {
            public void actionPerformed( ActionEvent e ) {
                CreateUserPresenter createUserPresenter = new CreateUserPresenter( new CreateUserViewImpl( null, true) );
                createUserPresenter.getView().asWidget().setVisible( true );
            }
        };
        getView().addNewUserListener( newUser );

        recoverPassword = new ActionListener() {
            public void actionPerformed( ActionEvent e ) {            
            getView().showOK( getView().PASSWORD,
                    "<html>La contraseña, ha sido enviada a su correo electrónico.</html>",
                    "Recuperar Contraseña" );
            }
        };
        getView().addRecoverPasswordListener( recoverPassword );

        login = new ActionListener() {
            public void actionPerformed( ActionEvent e ) {
                if ( validate() ) {
                    Person person = service.getPersonByDocument( getView().getDocument(), getView().getDocumentType() );
                    Tpdisenio2009App.loggedUser = person;
                    if (person != null && person instanceof User && ((User)person).getFantasyTeam() == null) {
                        CreateFantasyTeamViewImpl createTeamView = new CreateFantasyTeamViewImpl(null, true);
                        CreateFantasyTeamPresenter createTeamPresenter = new CreateFantasyTeamPresenter(createTeamView);
                        createTeamPresenter.getView().asWidget().setVisible(true);
                    }
                    getView().asWidget().setVisible( false );
                }
            }
        };
        getView().addLoginListener( login );


        documentTypeChange = new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
            }
        };
        getView().addDocumentTypeChangeListener( documentTypeChange );
    }

    public void unbind() {

        if ( exitAPP != null )
            getView().removeExitAPPListener( exitAPP );
        if ( documentTypeChange != null)
            getView().removeDocumentTypeChangeListener( documentTypeChange );
        if ( login != null )
            getView().removeLoginListener( login );
        if ( newUser != null )
            getView().addNewUserListener( newUser );
        if ( recoverPassword != null )
            getView().removeRecoverPasswordListener( recoverPassword );
    }

}
